package halberd.filter;

import halberd.DataType;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;

/**
 * 西格玛增强
 * 
 * @author jiang
 *
 */
public class SigmaFilter {
	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		sigma(input.getDatas(), result.getDatas(), input.getWidth(), input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if (input == null) {
			return false;
		}
		DataType dt = input.getDataType();
		if (dt == DataType.RGB) {
			return true;
		}
		if (dt == DataType.RGBA) {
			return true;
		}
		return false;
	}

	private void sigma(int[][][] src, int[][][] dst, int w, int h) {
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				int r, g, b;
				r = src[i][j][0];
				g = src[i][j][1];
				b = src[i][j][2];
				double dr = r / 255.0;
				double dg = g / 255.0;
				double db = b / 255.0;
				dr = 255 / (1 + Math.exp(-8 * (dr - 0.5)));
				dg = 255 / (1 + Math.exp(-8 * (dg - 0.5)));
				db = 255 / (1 + Math.exp(-8 * (db - 0.5)));
				r = (int) dr;
				g = (int) dg;
				b = (int) db;
				dst[i][j][0] =  r;
				dst[i][j][1] =  g;
				dst[i][j][2] =  b;
			}
		}
	}
}
